using System;
using System.Data.SqlClient;

namespace MsSqlSpatial.Utility
{
	public class ConnectionOptions
	{
		public ConnectionOptions()
		{
		}

		public ConnectionOptions(string server, string database, string login, string password)
		{
			this.Server = server;
			this.Database = database;
			this.Login = login;
			this.Password = password;
		}

		/// <summary>
		/// Database server address and instance. 
		/// </summary>
		public string Server;

		/// <summary>
		/// Database name.
		/// </summary>
		public string Database;

		/// <summary>
		/// Database login name. If not specified for SQL Server, 
		/// it uses Windows authentication (SSPI).
		/// </summary>
		public string Login;

		public string Password;

		/// <summary>
		/// Specifies whether the connection is to a SQL Express user instance or not
		/// </summary>
		public bool UserInstance;

		/// <summary>
		/// If true, the <see cref="Database"/> will be attached as a file, otherwise it will be specified as the initial catalogue
		/// </summary>
		public bool AttachAsFile;

		internal string GetSqlServerConnectionString()
		{
			SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
			if (AttachAsFile)
				builder.AttachDBFilename = Database;
			else
				builder.InitialCatalog = Database;
			builder.DataSource = Server;
			builder.IntegratedSecurity = string.IsNullOrEmpty(this.Login);
			if(!string.IsNullOrEmpty(Login))
			{
				builder.UserID = Login;
				builder.Password = Password;
			}
			builder.UserInstance = UserInstance;
			return builder.ConnectionString;
		}

		internal string GetPostGisConnectionString()
		{
			string[] parts = Server.Split(':');
			string server = parts[0];
			string port = "5432";
			if (parts.Length > 1)
				port = parts[1];
			return string.Format("Server={0};Port={1};Database={2};User Id={3};Password={4};Encoding=UNICODE;", server, port, Database, Login, Password);
		}
	}
}
